import {KeywordModel} from "../../models/keyword.js"
import { BookModel } from "../../models/book.js"
import { paginationBev } from "../behaviors/pagination.js"

const keywordModel = new KeywordModel()
const bookModel = new BookModel()

// components/search/index.js
Component({
  /**
   * 组件的属性列表
   */
  behaviors: [paginationBev],
  properties: {
    more:{
      type:String,
      observer:'loadMore'
    }
  },

  /**
   * 组件的初始数据
   */
  data: {
    historyWord:[],
    hotWords:[],
    // dataArray:[],
    searching:false,
    q:'',
    loading:false,
    loadingCenter:false
  },

  attached(){
    // const historyWords = keywordModel.getHistory()
    // const hotWords = keywordModel.getHot()
    this.setData({
      historyWords: keywordModel.getHistory()
    })
    keywordModel.getHot().then(res=>{
      this.setData({
        hotWords:res.hot
      })
      console.log(res)
    })
  },
  /**
   * 组件的方法列表
   */
  methods: {
    onConfirm(event){
      this._showResult()
      this._showLoadingCenter()
      // this.initialize()
      // const word = event.detail.value
      // 向服务器请求数据
      const q = event.detail.value || event.detail.text
      // console.log(event)
      bookModel.search(0,q).then(res=>{
        this.setMoreData(res.books)
        this.setTotal(res.total)
        this.setData({ 
          // dataArray: res.books,
          q:q
        })
        keywordModel.addToHistory(q);
        this._hideLoadingCenter()
      })
    },
    _showLoadingCenter(){
      this.setData({
        loadingCenter:true
      })
    },
    _hideLoadingCenter(){
      this.setData({
        loadingCenter: false
      })
    },
    _showResult(){
      this.setData({
        searching: true
      })
    },
    onDelete(event){
      this.setData({
        searching: false,
        q:''
      })
      this.initialize()
    },
    // 下拉加载两种方式
    // srcoll-view  page onReachBottom
    loadMore() {
      // console.log(11)
      // const length = this.data.dataArray.length
      if (!this.data.q){
        return
      }
      if (this.isLoked()){
        return
      }
      if(this.hasMore()){
        // this.data.loading = true
        this.locked()
        bookModel.search(this.getCurrentStart(), this.data.q)
          .then(res => {
            // this.data.dataArray
            // res.book
            // const tempArray = this.data.dataArray.concat(res.books)
            this.setMoreData(res.books)
            // this.setData({
            //   dataArray: tempArray
            // })
            // this.data.loading = false
            this.unLocked()
          },()=>{
            this.unLocked()
          })
      }
    },
    
    onCancel(event) {
      this.initialize()
      this.triggerEvent('cancel', {}, {})
    },
  }
})
